package com.xxhui.screenshotdemo.server;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.WindowManager;
import android.widget.LinearLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MyService extends Service {

    private static final String TAG = "MyServer" ;
    private WindowManager windowManager;
    private WindowManager.LayoutParams params;

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        windowManager = ((WindowManager) getSystemService(WINDOW_SERVICE));
        view();
        return super.onStartCommand(intent, flags, startId);
    }

    private void view() {

        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                PixelFormat.TRANSLUCENT);
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        params.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        ;
        params.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;// 透明状态栏

        LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setDrawingCacheEnabled(true);
        linearLayout.buildDrawingCache();
        Bitmap bitmap = linearLayout.getDrawingCache();
        Log.e(TAG, "view: "+ Environment.getExternalStorageDirectory()+"shot.png");
        if (bitmap!=null) {
            File file = new File(Environment.getExternalStorageDirectory(), "shot.png");
            Log.e(TAG, "view: "+Environment.getExternalStorageDirectory()+"shot.png");
            try {
                FileOutputStream stream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                stream.flush();
                stream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        linearLayout.setBackgroundColor(Color.argb(200, 89, 89, 89));

        windowManager.addView(linearLayout, params);
    }


}
